import * as jwt from 'jsonwebtoken';
import { MyError } from './myError';
interface tokenArgs<T=any> {
    data: T;
    /**
     * 有效期，单位:天
     *
     * @type {number}
     * @memberof tokenArgs
     */
    exp: number;
}
const secret = 'hilton-secret';
/**
 * 生成jwtToken
 * 
 * @param {*} profile 
 * @returns 
 */
function genJwtToken(src: tokenArgs) {
    return jwt.sign({
        exp: Math.floor(Date.now() / 1000) + (60 * 60 * 24 * src.exp),//7天过期
        data: src.data
    }, secret);
}

/**
 * 解密token获得数据
 *
 * @param {string} token
 * @returns
 */
function decodeJwtToken(token: string) {
    return new Promise((resolve, reject) => {
        jwt.verify(token, secret, (err, decode) => {
            if (err) {
                if (err.name == 'TokenExpiredError') {
                    return reject(new MyError({code:1002,message:'token过期'}));
                }else{
                    return reject(new MyError({code:1002,message:'token无效'}));
                }
            }
            resolve(decode);
        });
    });
}
export { genJwtToken,decodeJwtToken }